import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mobpush_plugin/mobpush_plugin.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:jyofservice/init/login_form_field.dart';
import 'package:dio/dio.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:jyofservice/fluro/NavigatorUtil.dart';
import 'package:jyofservice/util/AesUtil.dart';
import 'package:jyofservice/util/LoadingScaffold.dart';
import 'package:jyofservice/util/webconfig.dart';
import 'package:flutter/gestures.dart';
import 'package:jyofservice/yinsizhengce/AgreementPage.dart';
import 'package:jyofservice/init/theme.dart' as theme;

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  String? baseUrl;

  //手机号文本字段的控制器
  final _phoneController = TextEditingController();

  //密码文本字段的控制器
  final _pwdController = TextEditingController();

  //手机号文本字段是否符合格式
  bool _phoneActivation = false;

  //密码文本字段是否符合格式
  bool _pwdActivation = false;
  late SharedPreferences sharedPreferences;
  var _currentPage = 0;

  //隐私协议是否显示
  bool agreement = false;
  bool reconfirm = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    getAgreement().then((data) {
      if (mounted) {
        setState(() {
          agreement = data;
        });
      }
    });
  }

  Future getAgreement() async {
    sharedPreferences = await SharedPreferences.getInstance();
    var _agreement = sharedPreferences.getBool("agreement");

    if (_agreement == null) {
      sharedPreferences.setBool("agreement", true);
      _agreement = sharedPreferences.getBool("agreement");
    }

    return _agreement;
  }

  @override
  Widget build(BuildContext context) {

    List<Widget> childrens = [];
    final _mainConatiner = Scaffold(
        body: Column(
      children: <Widget>[
        Expanded(
          child: Container(
            color: Colors.white,
//            decoration: new BoxDecoration(
//              gradient: theme.Theme.primaryGradient,
//            ),
            width: ScreenUtil().setWidth(750),
            height: double.infinity,
            child: SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  Container(
                    child: Image.asset(
                      'images/juxing875.png',
                      fit: BoxFit.fill,
                    ),
                    width: ScreenUtil().setWidth(750),
                    height: ScreenUtil().setHeight(500),
                  ),
                  SizedBox(
                    height: ScreenUtil().setHeight(60),
                  ),
                  Container(
                    height: ScreenUtil().setHeight(100),
                    width: ScreenUtil().setWidth(600),
                    decoration: BoxDecoration(
                        color: Color(0xFFeeeeee),
                        borderRadius: BorderRadius.all(
                          Radius.circular(ScreenUtil().setHeight(50)),
                        )),
                    child: Row(
                      children: <Widget>[
                        Expanded(
                            child: Container(
                                decoration: _currentPage == 0
                                    ? BoxDecoration(
                                        gradient: theme.Theme.primaryGradient,
                                        borderRadius: BorderRadius.all(
                                          Radius.circular(
                                              ScreenUtil().setHeight(50)),
                                        ))
                                    : null,
                                child: Center(
                                  child: TextButton(
                                      onPressed: () {
                                        if (mounted) {
                                          setState(() {
                                            _currentPage = 0;
                                          });
                                        }
                                      },
                                      child: Text(
                                        '客服',
                                        style: TextStyle(
                                            fontSize: 16,
                                            color: _currentPage == 0
                                                ? Colors.white
                                                : Colors.black38),
                                      )),
                                ))),
                        Expanded(
                            child: Container(
                                decoration: _currentPage == 1
                                    ? BoxDecoration(
                                        gradient: theme.Theme.primaryGradient,
                                        borderRadius: BorderRadius.all(
                                          Radius.circular(
                                              ScreenUtil().setHeight(50)),
                                        ))
                                    : null,
                                child: Center(
                                  child: TextButton(
                                      onPressed: () {
                                        if (mounted) {
                                          setState(() {
                                            _currentPage = 1;
                                          });
                                        }
                                      },
                                      child: Text(
                                        '收费',
                                        style: TextStyle(
                                            fontSize: 16,
                                            color: _currentPage == 1
                                                ? Colors.white
                                                : Colors.black38),
                                      )),
                                )))
                      ],
                    ),
                  ),
                  SizedBox(
                    height: ScreenUtil().setHeight(60),
                  ),
                  Container(
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.all(Radius.circular(20))),
                      child: Stack(
                        alignment: Alignment(0.1, 1.3),
                        children: <Widget>[
                          Container(
                            width: ScreenUtil().setWidth(700),
                            height: ScreenUtil().setWidth(400),
                            alignment: Alignment.center,
                            child: Column(
                              children: <Widget>[
                                SizedBox(
                                  height: ScreenUtil().setHeight(50),
                                ),
                                Container(
                                  color: Colors.white,
                                  width: ScreenUtil().setWidth(600),
                                  child: LoginFormField(
                                    prefixIcon: Icon(
                                      Icons.person,
                                      size: 30,
                                    ),
                                    hintText: "请输入用户名",
                                    textEditingController: _phoneController,
                                    maxLength: 11,
                                    isPwd: false,
                                    minLength: 1,
                                    legitimateCallback: () {
                                      if (mounted) {
                                        setState(() {
                                          _phoneActivation = true;
                                        });
                                      }
                                    },
                                    illegalCallback: () {
                                      if (mounted) {
                                        setState(() {
                                          _phoneActivation = false;
                                        });
                                      }
                                    },
                                  ),
                                ),
                                SizedBox(
                                  height: ScreenUtil().setHeight(30),
                                ),
// TODO: 实现“密码输入框”。
                                Container(
                                  color: Colors.white,
                                  width: ScreenUtil().setWidth(600),
                                  child: LoginFormField(
                                    prefixIcon: Icon(
                                      Icons.lock,
                                      size: 30,
                                    ),
                                    hintText: "请输入密码",
                                    isPwd: true,
                                    textEditingController: _pwdController,
                                    maxLength: 20,
                                    minLength: 1,
                                    legitimateCallback: () {
                                      if (mounted) {
                                        setState(() {
                                          _phoneActivation = true;
                                        });
                                      }
                                    },
                                    illegalCallback: () {
                                      if (mounted) {
                                        setState(() {
                                          _phoneActivation = false;
                                        });
                                      }
                                    },
                                  ),
                                ),
                              ],
                            ),
                          ),
                          //TODO:登录按钮
                          SizedBox(
                            width: ScreenUtil().setWidth(500),
                            height: ScreenUtil().setWidth(120),
                            child: new Card(
                              shape: const RoundedRectangleBorder(
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(10.0))),
                              color: Colors.blue,
                              elevation: 10.0,
                              child: new TextButton(
                                  onPressed: _loginButton,
                                  child: new Padding(
                                    padding: new EdgeInsets.all(10.0),
                                    child: Text(
                                      '登录',
                                      textAlign: TextAlign.center,
                                      style: TextStyle(
                                        fontSize: 20.0,
                                        letterSpacing: 26,
                                        color: Colors.white,
                                      ),
                                    ),
                                  )),
                            ),
                          ),
                        ],
                      ))
                ],
              ),
            ),
          ),
        ),
        Container(
          alignment: Alignment.center,
          padding: EdgeInsets.only(bottom: ScreenUtil().bottomBarHeight),
          color: Colors.white,
          width: ScreenUtil().setWidth(750),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Radio(value: true, groupValue: true, onChanged: (dynamic val) {}),
              RichText(
                text: TextSpan(
                    style: TextStyle(
                        fontSize: ScreenUtil().setSp(26),
                        color: Colors.black45),
                    text: '已阅读并且同意',
                    children: [
                      TextSpan(
                        text: '《隐私政策'
                            '》',
                        style: TextStyle(
                            fontSize: ScreenUtil().setSp(26),
                            color: Colors.blue),
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            print('点击了服务条款');

                            Navigator.push(context,
                                MaterialPageRoute(builder: (context) {
                              return AgreementPage();
                            }));
                          },
                      )
                    ]),
              ),
            ],
          ),
        )
      ],
    ));
    childrens.add(_mainConatiner);
    final _showPrivacyPolicyAlert = Container(
        color: Colors.black12.withOpacity(0.6),
        child: Column(
          children: <Widget>[
            SizedBox(
              height: ScreenUtil().setHeight(300),
            ),
            Center(
              child: Container(
                  padding: EdgeInsets.all(10.0),
                  width: ScreenUtil().setWidth(600),
                  height: ScreenUtil().setWidth(900),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(10.0)),
                  child: Column(
                    children: <Widget>[
                      Container(
                          child: RichText(
                              text: TextSpan(
                                  style: TextStyle(
                                      fontSize: ScreenUtil().setSp(40),
                                      color: Colors.black),
                                  text: '温馨提示'))),
                      SizedBox(
                        height: 10.0,
                      ),
                      SingleChildScrollView(
                          child: RichText(
                              text: TextSpan(
                                  style: TextStyle(
                                      fontSize: ScreenUtil().setSp(30),
                                      color: Colors.black),
                                  text: '欢迎使用交运客服语音App！\n'
                                      '为了能给您提供更好的服务,我们会对您的个人信息进行收集、使用和保护。\n'
                                      '为保证您可以使用本应用所有功能,请同意并接受我们的',
                                  children: [
                            TextSpan(
                              text: '《隐私政策'
                                  '》',
                              style: TextStyle(
                                  fontSize: ScreenUtil().setSp(30),
                                  color: Colors.blue),
                              recognizer: TapGestureRecognizer()
                                ..onTap = () {
                                  print('点击了服务条款');

                                  Navigator.push(context,
                                      MaterialPageRoute(builder: (context) {
                                    return AgreementPage();
                                  }));
                                },
                            ),
                            TextSpan(
                                style: TextStyle(
                                    fontSize: ScreenUtil().setSp(30),
                                    color: Colors.black),
                                text: '后, 更好的使用和体验我们的服务! \n\n'),
                            TextSpan(
                                style: TextStyle(
                                    fontSize: ScreenUtil().setSp(30),
                                    color: Colors.black38),
                                text:
                                    '如您同意此协议,请点击同意并开始使用我们的产品和服务,我们会全力保护您的个人信息安全。'),
                          ]))),
                      Expanded(child: Container()),
                      Container(
                        width: ScreenUtil().setWidth(500),
                        height: ScreenUtil().setWidth(80),
                        padding: EdgeInsets.all(2),
                        child: TextButton(
                            style: ButtonStyle(
                              //外边框装饰 会覆盖 side 配置的样式
                              shape: WidgetStateProperty.all(StadiumBorder()),
                              //背景颜色
                              backgroundColor:
                              WidgetStateProperty.resolveWith((states) {
                                //设置按下时的背景颜色
                                // if (states.contains(MaterialState.pressed)) {
                                //   return Colors.blue[200];
                                // }
                                //默认使用背景颜色
                                return Colors.blue;
                              }),
                            ),
                            onPressed: () {
                              if (mounted) {
                                setState(() {
                                  sharedPreferences.setBool("agreement", false);
                                  agreement = false;
                                });
                              }
                            },
                            child: Text(
                              '同意',
                              style: TextStyle(color: Colors.white),
                            )),
                      ),
                      Container(
                        width: ScreenUtil().setWidth(500),
                        height: ScreenUtil().setWidth(80),
                        padding: EdgeInsets.all(2),
                        child: TextButton(
                            style: ButtonStyle(
                              //外边框装饰 会覆盖 side 配置的样式
                              shape: WidgetStateProperty.all(StadiumBorder()),
                              //背景颜色
                              backgroundColor:
                              WidgetStateProperty.resolveWith((states) {
                                //设置按下时的背景颜色
                                // if (states.contains(MaterialState.pressed)) {
                                //   return Colors.blue[200];
                                // }
                                //默认使用背景颜色
                                return Colors.black12;
                              }),
                            ),
                            onPressed: () {
                              if (mounted) {
                                setState(() {
                                  sharedPreferences.setBool("agreement", true);
                                  agreement = false;
                                  reconfirm = true;
                                });
                              }
                            },
                            child: Text(
                              '不同意',
                              style: TextStyle(color: Colors.black),
                            )),
                      ),
                      SizedBox(
                        height: 20.0,
                      ),
                    ],
                  )),
            ),
          ],
        ));
    if (agreement) {
      childrens.add(_showPrivacyPolicyAlert);
    }
    final _showAlert = Container(
        color: Colors.black12.withOpacity(0.6),
        child: AlertDialog(
          title: Text('您需要同意本隐私政策才能继续使用'),
          content: Text(
            '若您不同意本隐私政策, 很遗憾我们将无法为您提供服务。',
            style: TextStyle(color: Colors.black38),
          ),
          actions: <Widget>[
            TextButton(
                style: ButtonStyle(
                  //外边框装饰 会覆盖 side 配置的样式
                  shape: MaterialStateProperty.all(StadiumBorder()),
                  //背景颜色
                  backgroundColor: MaterialStateProperty.resolveWith((states) {
                    //设置按下时的背景颜色
                    // if (states.contains(MaterialState.pressed)) {
                    //   return Colors.blue[200];
                    // }
                    //默认使用背景颜色
                    return Colors.blue;
                  }),
                ),
                onPressed: () {
                  if (mounted) {
                    setState(() {
                      agreement = true;
                      reconfirm = false;
                    });
                  }
                },
                child: Text(' 查看协议 '))
          ],
        ));

    if (reconfirm) {
      childrens.add(_showAlert);
    }

    return Stack(children: childrens);
  }

  void _loginButton() {
    if (_phoneController.text.toString() == "" ||
        _pwdController.text.toString() == "") {
      Fluttertoast.showToast(msg: "用户名或密码不能为空");
    } else {
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (BuildContext context) {
            return LoadingDialog(
              text: "账号登录中…",
            );
          });
      if (_currentPage == 1) {
        //收费登录
        sfLogin().then((value) {
          if (value["resultCode"] == "100") {
            //登录状态
            sharedPreferences.setString("key", "sfjc");
            sharedPreferences.setString("username", value["real_name"]);
            sharedPreferences.setString("rolename", value["role_name"]);
            Navigator.of(context).pop();
            NavigatorUtil.goSF(context);
          } else {
            Fluttertoast.showToast(msg: value["resultMsg"]);
            NavigatorUtil.goBack(context);
          }
        });
      } else {
        getLogin().then((onValue) {
          print(onValue);

          if (onValue["Code"] == "200") {
            sharedPreferences.setString("key", onValue["Data"]["key"]);
            sharedPreferences.setString("pwd", _pwdController.text.toString());
            sharedPreferences.setString(
                "username", _phoneController.text.toString());
            Fluttertoast.showToast(msg: "登录成功");
            AesUtil.decodeBase64(onValue["Data"]["key"]).then((aes) {
              sharedPreferences.setString("id", aes);
              print("hahahah:" + aes.toString());

              if (aes != null) {
                MobpushPlugin.restartPush();
                MobpushPlugin.setAlias(aes)
                    .then((Map<String, dynamic> aliasMap) {
                  String? res = aliasMap['res'];
                  String? error = aliasMap['error'];
                  String? errorCode = aliasMap['errorCode'];
                  print(
                      "$aes>>>>>>>>>>>>>>>>>>>>>>> setAlias$aes -> res: $res error: $error");
                });
                showNotification();
              }
            });
          } else {
            Fluttertoast.showToast(msg: onValue["Msg"]);
            NavigatorUtil.goBack(context);
          }
        });
      }
    }
  }

  Future getLogin() async {
    String aesData = await AesUtil.encodeBase64();
    var data = {
      "username": _phoneController.text.toString(),
      "password": _pwdController.text.toString(),
      "ClientType": "phone",
      "ClientKey": aesData
    };
    print('${WebConfig().baseUrl + "Login/login"}=${data.toString()}');

    Response response =
        await Dio().post(WebConfig().baseUrl + "Login/login", data: data);
    return response.data;
  }

  Future showNotification() async {
    final option = await showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return new AlertDialog(
            title: Text('推送提醒'),
            content: Text('为功能正常使用，请确保打开了通知权限？'),
            actions: <Widget>[
              TextButton(
                child: Text('确定'),
                onPressed: () {
                  Navigator.pop(context);
                  Navigator.of(context).pop();
                  NavigatorUtil.goHome(context);
                },
              ),
            ],
          );
        });
  }

  Future sfLogin() async {
    Response response = await Dio().get(WebConfig().jichaUrl +
        "method=Appppp_loooooogin&username=" +
        _phoneController.text.toString() +
        "&password=" +
        _pwdController.text.toString());
    return response.data;
  }
}
